import { ENV } from '.env.js'
import { isArrayFn } from './util'

// 请求拦截器
uni.addInterceptor('request', {
  invoke(args) {
		if(args.url.indexOf('https://') === -1 && args.url.indexOf('http://') === -1) {
			args.url = ENV.BASE_API + args.url
		}
  },
  success(args) {
    // console.log('success', args)
  },
  fail(err) {
    // console.log('interceptor-fail',err)
  },
  complete(res) {
    // console.log('interceptor-complete',res)
  }
})

// 请求函数
function request(config) {
  return new Promise((resolve, reject) => {
    uni.request({
      url: config.url,
      data: config.data || {},
      header: {
        [ENV.HEAD]: uni.getStorageSync('token') || '',
        'content-type': config.contentType || 'application/json;charset=utf-8',
        ...config.header,
      },
      method: config.method || 'POST',
      dataType: config.dataType || 'JSON',
      success: async (res) => {
        // #ifdef APP-PLUS || H5
        var data = res.data
        // #endif
        // #ifdef MP-WEIXIN
				
				// const fixedString = res.data
				//   .replace(/\\/g, '\\\\') // 转义所有反斜杠
				
        // var data = JSON.parse((fixedString))
        var data = JSON.parse((res.data))
        // #endif
        try {
          if(isArrayFn(data) && data.length && config.url != '/K3Cloud/Kingdee.BOS.WebApi.ServicesStub.AuthService.ValidateUser.common.kdsvc') {
            if(isArrayFn(data[0]) && data[0].length) {
              const Result = data[0][0].Result
              if(Result && Result.ResponseStatus) {
                const ResponseStatus = Result.ResponseStatus
                if(ResponseStatus) {
                  if(!ResponseStatus.IsSuccess) {
                    try {
                      if(isArrayFn(ResponseStatus.Errors) && ResponseStatus.Errors.length) {
                        const err = ResponseStatus.Errors[0]
                        if(err.Message == '会话信息已丢失，请重新登录') {
                          // 清除登录缓存
                          uni.removeStorageSync('token')
                          setTimeout(() => {
                            uni.reLaunch({
                              url: '/pages/login/login'
                            })
                          }, 1000)
                        }
                        uni.showToast({
                          icon: 'none',
                          title: err.Message,
                        })
                      }
                    } catch(e) {
                      console.log('Message', e);
                    }
                  }
                }
              }
            }
          } else if(data.Result && data.Result.ResponseStatus && !data.Result.ResponseStatus.IsSuccess) {
            const Result = data.Result
            if(Result && Result.ResponseStatus) {
              const ResponseStatus = Result.ResponseStatus
              if(ResponseStatus) {
                if(!ResponseStatus.IsSuccess) {
                  uni.hideLoading();
                  try {
                    if(isArrayFn(ResponseStatus.Errors) && ResponseStatus.Errors.length) {
                      const err = ResponseStatus.Errors[0]
                      if(err.Message == '会话信息已丢失，请重新登录') {
                        // 清除登录缓存
                        uni.removeStorageSync('token')
                        setTimeout(() => {
                          uni.reLaunch({
                            url: '/pages/login/login'
                          })
                        }, 1000)
                      }
                      uni.showToast({
                        icon: 'none',
                        title: err.Message,
                      })
                    }
                  } catch(e) {
                    console.log('Message', e);
                  }
                }
              }
            }
          }
        } catch(e) {
          uni.hideLoading();
          console.log('ResponseStatus', e);
        }
        uni.hideLoading();
        resolve(data)
      },
      fail: (err) => {
        uni.showToast({
          icon: 'none',
          title: '接口请求失败'
        })
        reject(err)
      },
      complete: (res) => {
        try {
          config.complete(res)
        } catch (e) {
          // TODO handle the exception
        }
      }
    })
  })
}

export default request
